use alloc::borrow::ToOwned;
use alloc::string::String;
use alloc::vec::Vec;

pub const INVALID_SEQ: u32 = 0;
pub const INVALID_MSG_ID: u64 = 0;

#[derive(Debug, Clone)]
pub struct QMessage {
    pub id: u64,
    pub topic: String,
    pub payload: Vec<u8>,
    pub req_id: u32,
    pub created_time: i64,
    pub consume_count: u32,
}

pub struct QMessageInfo {
    pub id: u64,
    pub topic: String,
    pub req_id: u32,
    pub created_time: i64,
}

pub struct VarData {
    pub num: u8,
    pub data: Vec<u8>,
}

impl VarData {
    pub fn new(size: u32) -> VarData {
        let mut data = Vec::with_capacity(size as usize);
        unsafe {
            data.set_len(size as usize);
        }
        Self { num: 0, data }
    }
    pub fn append(&mut self, data: &[u8]) -> Result<(), String> {
        if 4 + data.len() > self.data.len() {
            return Err("overflow".to_owned());
        }
        self.push_len(data.len());
        self.data.append(&mut Vec::from(data));
        Ok(())
    }

    pub fn data(&self) -> &[u8] {
        self.data.as_slice()
    }

    fn push_len(&mut self, len: usize) {
        let d = [
            (len % 0xff) as u8,
            ((len >> 8) & 0xff) as u8,
            ((len >> 16) & 0xff) as u8,
            ((len >> 24) & 0xff) as u8,
        ];
        self.data.append(&mut Vec::from(d));
    }
}
